local skynet = require "skynet"
local socket = require "skynet.socket"
local service = require "skynet.service"
local websocket = require "http.websocket"
log = require "log" 
local handle = {}
local MODE = ...


    function handle.connect(id)
        log.info("ws connect from: " .. tostring(id))
    end

    function handle.handshake(id, header, url)
        local addr = websocket.addrinfo(id)
        log.info("ws handshake from: " .. tostring(id), "url", url, "addr:", addr)
        log.info("----header-----")
        for k,v in pairs(header) do
            log.info(k,v)
        end
        log.info("--------------")
    end

    function handle.message(id, msg, msg_type)
        assert(msg_type == "binary" or msg_type == "text")
        log.info("msg=", msg)
       for i = 1, 100000 do
        skynet.sleep(100*60*10)
        websocket.write(id, "skynet server message!")
       end
    
    end

    function handle.ping(id)
        log.info("ws ping from: " .. tostring(id) .. "\n")
    end

    function handle.pong(id)
        log.info("ws pong from: " .. tostring(id))
    end

    function handle.close(id, code, reason)
        log.info("ws close from: " .. tostring(id), code, reason)
    end

    function handle.error(id)
        log.info("ws error from: " .. tostring(id))
    end

    skynet.start(function ()
        skynet.dispatch("lua", function (_,_, id, protocol, addr)
            log.info("id=",id)
            log.info("protocol=",protocol)

            local ok, err = websocket.accept(id, handle, protocol, addr)
            if not ok then
                log.info(err)
            end
        end)
    end)

